<template>
  <div class="showTable">
    <div class="flx-justify-between params_line">
      <div class="flx-align-center p_left">
        <el-input v-model="paramsObj.myName"></el-input>
        <el-button class="search_btn">查询</el-button>
      </div>
      <div class="flx-align-center p_right">
        <el-button @click="deselectRows">取消选择</el-button>
      </div>
    </div>
    <div ref="containerRef">
      <ag-grid-vue
        class="ag-theme-xxl"
        :style="`height: ${boxHeight}px`"
        :columnDefs="columnDefs.value"
        :defaultColDef="defaultColDef"
        rowSelection="multiple"
        animateRows="false"
        @cell-clicked="cellWasClicked"
        @grid-ready="onGridReady"
      >
      </ag-grid-vue>
    </div>
  </div>
</template>

<script setup lang="ts">
import { AgGridVue } from "ag-grid-vue3";
import { reactive, onMounted, onUnmounted, ref } from "vue";
//变量
let boxHeight = ref(200);
const containerRef = ref();
const paramsObj = reactive({
  myName: "小溪流"
});
const gridApi = ref(null);
const columnDefs = reactive({
  value: [
    {
      field: "",
      headerCheckboxSelection: true,
      showDisabledCheckboxes: true,
      checkboxSelection: params => {
        return true;
      },
      width: 40,
      sortable: false,
      filter: false
    },
    { field: "make", flex: 1 },
    { field: "model", flex: 1 },
    { field: "price", flex: 1 }
  ]
});
const defaultColDef = {
  sortable: false,
  filter: false
};
//生命周期
onMounted(() => {
  window.addEventListener("resize", changeAgHeight);
  changeAgHeight();
  initTableData();
});
onUnmounted(() => {
  window.removeEventListener("resize", changeAgHeight);
});

/**
 * 获取表格数据
 */
const initTableData = () => {
  fetch("https://www.ag-grid.com/example-assets/row-data.json")
    .then(result => result.json())
    .then(remoteRowData => {
      gridApi.value.sizeColumnsToFit();
      gridApi.value.setRowData(remoteRowData);
    });
};

// Obtain API from grid's onGridReady event
const onGridReady = params => {
  gridApi.value = params.api;
  console.log("gridApi.value", gridApi.value);
};

/**
 * 表格自适应高度
 */
const changeAgHeight = () => {
  boxHeight.value = document.documentElement.clientHeight - containerRef.value.getBoundingClientRect().top - 42;
};

/**
 * 点击了某一行
 */
const cellWasClicked = event => {
  console.log("cell was clicked", event);
};

/**
 * 删除所有选择
 */
const deselectRows = () => {
  gridApi.value.deselectAll();
};
</script>

<style lang="scss">
@import "./index.scss";
</style>
